package com.dragon.modules.yuegou.service.impl.member;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.entity.member.MemberGradeLogEntity;
import com.dragon.modules.yuegou.entity.member.TemplateGradeEntity;
import com.dragon.modules.yuegou.entity.member.TemplateGradeSetEntity;
import com.dragon.modules.yuegou.enums.member.MemberGradeLogGradeRule;
import com.dragon.modules.yuegou.enums.member.MemberGradeLogType;
import com.dragon.modules.yuegou.enums.member.TemplateGradeParamParamType;
import com.dragon.modules.yuegou.enums.member.TemplateGradeParamTimeAccuracy;
import com.dragon.modules.yuegou.enums.member.TemplateGradeSetGradeCondition;
import com.dragon.modules.yuegou.enums.member.TemplateSetGradeRule;
import com.dragon.modules.yuegou.enums.member.TemplateSetStatus;
import com.dragon.modules.yuegou.mapper.member.TemplateGradeMapper;
import com.dragon.modules.yuegou.model.busd.District;
import com.dragon.modules.yuegou.model.member.MemberCardLevel;
import com.dragon.modules.yuegou.model.member.TemplateGrade;
import com.dragon.modules.yuegou.model.member.TemplateGradeParam;
import com.dragon.modules.yuegou.model.member.TemplateSet;
import com.dragon.modules.yuegou.query.member.MemberCardLevelQuery;
import com.dragon.modules.yuegou.query.member.TemplateGradeParamQuery;
import com.dragon.modules.yuegou.query.member.TemplateGradeQuery;
import com.dragon.modules.yuegou.query.member.TemplateGradeSetQuery;
import com.dragon.modules.yuegou.query.member.TemplatePretendQuery;
import com.dragon.modules.yuegou.query.member.TemplateRightsQuery;
import com.dragon.modules.yuegou.query.order.OrderMemberGradeQuery;
import com.dragon.modules.yuegou.query.points.PointSumQuery;
import com.dragon.modules.yuegou.service.busd.DistrictService;
import com.dragon.modules.yuegou.service.member.MemberCardLevelService;
import com.dragon.modules.yuegou.service.member.MemberGradeLogService;
import com.dragon.modules.yuegou.service.member.TemplateGradeParamService;
import com.dragon.modules.yuegou.service.member.TemplateGradeService;
import com.dragon.modules.yuegou.service.member.TemplateGradeSetService;
import com.dragon.modules.yuegou.service.member.TemplatePretendService;
import com.dragon.modules.yuegou.service.member.TemplateRightsService;
import com.dragon.modules.yuegou.service.member.TemplateSetService;
import com.dragon.modules.yuegou.service.order.OrderService;
import com.dragon.modules.yuegou.service.points.DetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员卡等级设置 服务实现
 *
 * @author pbuilder generated
 * @version 2.0
 */
@Slf4j
@Service("memTemplateGradeService")
public class TemplateGradeServiceImpl
		extends ServiceImpl<TemplateGradeMapper, TemplateGradeEntity>
		implements TemplateGradeService {

	@Autowired
	private TemplateGradeSetService templateGradeSetService;

	@Autowired
	private TemplateGradeParamService templateGradeParamService;

	@Autowired
	private TemplateRightsService templateRightsService;

	@Autowired
	private TemplatePretendService templatePretendService;

	@Autowired
	private MemberCardLevelService memberCardLevelService;

	@Autowired
	private TemplateSetService templateSetService;

	@Autowired
	private TemplateGradeService templateGradeService;

	@Autowired
	private DetailService detailService;

	@Autowired
	private OrderService orderService;

	@Autowired
	private DistrictService districtService;

	@Autowired
	private MemberGradeLogService memberGradeLogService;

	@Override
	public void saveTemplateGradeList(String templateSetId, List<TemplateGrade> grades) {
		TemplateGradeQuery query = new TemplateGradeQuery();
		query.setTemplateSetId(templateSetId);
		query.setDel(false);
		List<TemplateGradeEntity> olds = list(query.toQueryWrapper());

		for(TemplateGrade grade : grades) {
			if(StringUtils.isEmpty(grade.getId())) {
				// 新增
				grade.setId(IdWorker.getIdStr());
			}
			grade.setStatus(TemplateSetStatus.PUBLISH);
			save(grade);
		}

		if(CollectionUtils.isNotEmpty(olds)) {
			for(TemplateGradeEntity oldGrade : olds) {
				// 删除
				if(Boolean.FALSE.equals(exists(oldGrade,grades))) {
					// 会员卡等级设置
					removeById(oldGrade.getId());

					// 会员卡等级条件
					TemplateGradeSetQuery gradeSetQuery = new TemplateGradeSetQuery();
					gradeSetQuery.setTemplateSetId(templateSetId);
					gradeSetQuery.setTemplateGradeId(oldGrade.getId());
					templateGradeSetService.remove(gradeSetQuery.toQueryWrapper());

					// 会员卡等级条件参数
					TemplateGradeParamQuery gradeParamQuery = new TemplateGradeParamQuery();
					gradeParamQuery.setTemplateSetId(templateSetId);
					gradeParamQuery.setTemplateGradeId(oldGrade.getId());
					templateGradeParamService.remove(gradeParamQuery.toQueryWrapper());

					// 会员卡等级装扮
					TemplatePretendQuery pretendQuery = new TemplatePretendQuery();
					pretendQuery.setTemplateSetId(templateSetId);
					pretendQuery.setTemplateGradeId(oldGrade.getId());
					templatePretendService.remove(pretendQuery.toQueryWrapper());

					// 会员卡等级权益关联
					TemplateRightsQuery rightsQuery = new TemplateRightsQuery();
					rightsQuery.setTemplateSetId(templateSetId);
					rightsQuery.setTemplateGradeId(oldGrade.getId());
					templateRightsService.remove(rightsQuery.toQueryWrapper());
				}
			}
		}
	}

	private boolean exists(TemplateGradeEntity oldGrade,List<TemplateGrade> grades){
		boolean exists = false;
		for(TemplateGrade grade : grades) {
			if(oldGrade.getId().equals(grade.getId())) {
				// 修改
				exists = true;
				break;
			}
		}
		return exists;
	}

	@Override
	public void gradeRelegation(String busdId, String memberId) {
		try {
			if(StringUtils.isEmpty(busdId) || StringUtils.isEmpty(memberId)) {
				log.error("商圈ID和会员ID条件异常：商圈id={}，会员id={}", busdId, memberId);
				return;
			}
			log.debug(" == 对指定商圈与会员id的会员进行升降级处理 gradeRelegation ：商圈id={}，会员id={} == ", busdId, memberId);
			// 获取当前会员卡等级信息
			MemberCardLevel memberCardLevel = memberCardLevelService.getMemberCardLevel(busdId,memberId);
			if(null == memberCardLevel) {
				log.error("未获取到会员卡等级信息：商圈id={}，会员id={}", busdId, memberId);
				return;
			}

			// 获取会员卡模板设置
			TemplateSet templateSet = templateSetService.getTemplateSetByBusdId(busdId, TemplateSetStatus.PUBLISH);
			if(null == templateSet) {
				log.error("未获取到商圈对应的会员卡设置：商圈id={}，会员id={}", busdId, memberId);
				return;
			}

			// 会员卡对应等级条件
			TemplateGradeQuery gradeQuery = new TemplateGradeQuery();
			gradeQuery.setTemplateSetId(templateSet.getId());
			gradeQuery.setDel(false);
			QueryWrapper<TemplateGradeEntity> wrapper = gradeQuery.toQueryWrapper();
			wrapper.orderByAsc(TemplateGradeEntity.COL_SERIAL_NUMBER);
			List<TemplateGradeEntity> grades = templateGradeService.list(wrapper);
			if(CollectionUtils.isEmpty(grades)) {
				log.error("未获取到会员卡对应等级条件：商圈id={}，会员id={}，会员卡模板设置id={}", busdId, memberId, templateSet.getId());
				return;
			}

			// 获取当前会员对应的等级条件信息
			TemplateGradeEntity memberGrade = templateGradeService.getById(memberCardLevel.getGradeId());
			if(null == memberGrade) {
				log.error("未获取到当前会员对应的等级条件：商圈id={}，会员id={}，当前会员等级ID={}", busdId, memberId, memberCardLevel.getGradeId());
				return;
			}

			this.gradeRelegationDetail(busdId,memberId,memberCardLevel,templateSet,grades,memberGrade);
		} catch (Exception e) {
			log.error(" == gradeRelegation 对指定商圈id与会员id的会员进行升降级处理失败【FAILED】 ：商圈id={}，会员id={}，error={}。  == ", busdId, memberId, e.getMessage());
		}
	}

	private void gradeRelegationDetail(String busdId, String memberId,MemberCardLevel memberCardLevel,TemplateSet templateSet,List<TemplateGradeEntity> grades,TemplateGradeEntity memberGrade){

		StringBuilder reason = new StringBuilder();
		reason.append("当前商圈ID【" + busdId + "】，会员ID【" + memberId + "】，会员等级【" + memberCardLevel.getGradeName() + "】，当前会员成长值【"
				+ memberCardLevel.getGrowCount() + "】，当前等级升级规则【" + memberCardLevel.getGradeRule().getAlias() + "】。");


		TemplateGrade upgradeGrade = null;
		// 升级等级规则：成长值
		if(TemplateSetGradeRule.GROWTH.getCode().equals(templateSet.getGradeRule().getCode())) {
			upgradeGrade = this.gradeRelegationGrowth(grades,memberCardLevel,memberGrade,reason);
		} else {
			// 升级等级规则：指定条件
			upgradeGrade = this.gradeRelegationSpecified(busdId,memberId,grades,memberGrade,reason);
		}

		if(null != upgradeGrade) {
			// 更新会员卡等级表
			this.saveUpgradeGrade(busdId,memberId,upgradeGrade,memberCardLevel,templateSet,reason);
		}

	}
	private TemplateGrade gradeRelegationGrowth(List<TemplateGradeEntity> grades,MemberCardLevel memberCardLevel,TemplateGradeEntity memberGrade,StringBuilder reason){
		TemplateGrade upgradeGrade = null;
		Long growCount = memberCardLevel.getGrowCount();
		Integer serialNumber = memberGrade.getSerialNumber();
		for(TemplateGradeEntity grade : grades) {
			Long scoreEnd = grade.getScoreEnd() == null ? Long.MAX_VALUE : grade.getScoreEnd();
			if(growCount >= grade.getScoreStart() && growCount <= scoreEnd && serialNumber < grade.getSerialNumber()) {
				// 若当前会员卡成长值在指定等级条件范围，并且会员卡等级编号小于指定等级条件的等级编号，则升级，可升多级
				serialNumber = grade.getSerialNumber();
				upgradeGrade = new TemplateGrade();
				BeanUtils.copyProperties(grade, upgradeGrade);
				reason.append("当前会员满足会员等级【" + grade.getId() + grade.getName() + "】的成长值范围（" + grade.getScoreStart() + "-" + grade.getScoreEnd() + "）。");
			}
		}
		return upgradeGrade;
	}

	private TemplateGrade gradeRelegationSpecified(String busdId,String memberId, List<TemplateGradeEntity> grades,TemplateGradeEntity memberGrade,StringBuilder reason){
		TemplateGrade upgradeGrade = null;
		Integer serialNumber = memberGrade.getSerialNumber();
		// 升级等级规则：指定条件
		for(TemplateGradeEntity grade : grades) {
			if(serialNumber < grade.getSerialNumber()) {
				// 是否达到等级条件
				boolean reachGradeLevel = false;

				// 获取会员卡等级条件表
				TemplateGradeSetQuery gradeSetQuery = new TemplateGradeSetQuery();
				gradeSetQuery.setTemplateSetId(grade.getTemplateSetId());
				gradeSetQuery.setTemplateGradeId(grade.getId());
				gradeSetQuery.memGradeParamId().isNotNull();
				List<TemplateGradeSetEntity> gradeSets = templateGradeSetService.list(gradeSetQuery.toQueryWrapper());
				if(CollectionUtils.isEmpty(gradeSets)) {
					log.error("当前会员等级未设置会员卡等级条件：会员卡模板设置id={}，会员卡等级ID={}", grade.getTemplateSetId(), grade.getId());

				}else {
					reachGradeLevel = reachGradeLevel(gradeSets,busdId,memberId,reason);
					reason.append("，会员卡等级条件【" + gradeSets.get(0).getGradeCondition().getAlias() + "】");
				}

				// 判断当前等级条件是否满足
				if(reachGradeLevel) {
					serialNumber = grade.getSerialNumber();
					upgradeGrade = new TemplateGrade();
					BeanUtils.copyProperties(grade, upgradeGrade);
					reason.append("，满足当前会员等级【" + grade.getSerialNumber() + "|" + grade.getName() + "】。");
				}
			}
		}
		return upgradeGrade;
	}

	private boolean reachGradeLevel(List<TemplateGradeSetEntity> gradeSets,String busdId,String memberId,StringBuilder reason){
		boolean anyCondition = false;
		boolean allCondition = true;
		for(TemplateGradeSetEntity gradeSet : gradeSets) {

			// 判断是否满足当前会员卡等级条件
			boolean reachGradeSet = reachGradeSet(busdId, memberId, gradeSet, reason);

			// 判断等级条件：0-满足任一条件-ANY、1-满足所有条件-ALL
			if(TemplateGradeSetGradeCondition.ANY.equals(gradeSet.getGradeCondition())) {
				if(reachGradeSet) {
					return true;
				}
			} else {
				if(!reachGradeSet) {
					return false;
				}
			}
		}

		if(TemplateGradeSetGradeCondition.ANY.getCode().equals(gradeSets.get(0).getGradeCondition().getCode())) {
			return anyCondition;
		} else {
			return allCondition;
		}
	}


	private void saveUpgradeGrade(String busdId, String memberId,TemplateGrade upgradeGrade,MemberCardLevel memberCardLevel,TemplateSet templateSet,StringBuilder reason){
		// 更新会员卡等级表
		MemberCardLevel newCardLevel = new MemberCardLevel();
		newCardLevel.setGradeId(upgradeGrade.getId());
		newCardLevel.setGradeName(upgradeGrade.getName());
		newCardLevel.setModifiedTime(LocalDateTime.now());
		newCardLevel.setBeginTime(LocalDateTime.now());
		if (null != upgradeGrade.getIsDowngrade() && upgradeGrade.getIsDowngrade()
				&& upgradeGrade.getProtectionDays()!=null
				&& upgradeGrade.getProtectionDays()>0){
			newCardLevel.setEndTime(newCardLevel.getBeginTime().plusDays(Long.parseLong(upgradeGrade.getProtectionDays().toString())));
		}
		MemberCardLevelQuery cardLevelQuery = new MemberCardLevelQuery();
		cardLevelQuery.setId(memberCardLevel.getId());
		memberCardLevelService.update(newCardLevel, cardLevelQuery.toQueryWrapper());

		// 清除缓存
		memberCardLevelService.evict(busdId, memberId);

		// 创建会员等级更新日志
		MemberGradeLogEntity gradeLog = new MemberGradeLogEntity();
		gradeLog.setId(IdWorker.getIdStr());
		gradeLog.setBusdId(busdId);
		gradeLog.setMemberId(memberId);
		gradeLog.setType(MemberGradeLogType.VIP_UPGRADE);
		gradeLog.setGradeRule(MemberGradeLogGradeRule.from(templateSet.getGradeRule().getCode()));
		gradeLog.setBeforeGradeId(memberCardLevel.getGradeId());
		gradeLog.setBeforeGrade(memberCardLevel.getGradeName());
		gradeLog.setAlferGradeId(upgradeGrade.getId());
		gradeLog.setAfterGrade(upgradeGrade.getName());
		gradeLog.setReason(reason.toString());
		gradeLog.setCreatedTime(LocalDateTime.now());
		memberGradeLogService.save(gradeLog);
	}

	@Override
	public List<TemplateGrade> listGrade(String busdId) {
		TemplateGradeQuery gradeQuery = new TemplateGradeQuery();
		gradeQuery.busdId().eq(busdId);
		QueryWrapper<TemplateGradeEntity> wrapper = gradeQuery.toQueryWrapper();
		wrapper.orderByDesc(TemplateGradeEntity.COL_SERIAL_NUMBER);
		return this.list(wrapper).stream().map(TemplateGrade::new).collect(Collectors.toList());
	}

	@Override
	public void memberLevel(String busdId) {
		if (StringUtils.isNotEmpty(busdId)){
			District district = districtService.getDistrictById(busdId);
			memberDowngrade(district);
		}else {
			List<District> districtList = districtService.getDistrict();
			for (District district : districtList){
				memberDowngrade(district);
			}
		}
	}

	private void memberDowngrade(District district){
		TemplateSet templateSet = templateSetService.getTemplateSetByBusdId(district.getId(),TemplateSetStatus.PUBLISH);
		if (templateSet==null || StringUtils.isEmpty(templateSet.getId())){
			return;
		}
		//成长值无降级规则，直接跳出
		if(TemplateSetGradeRule.GROWTH.equals(templateSet.getGradeRule())) {
			return;
		}

		List<TemplateGrade> gradeList = this.listGrade(district.getId());
		for (TemplateGrade templateGrade : gradeList){
			//上一级等级
			TemplateGradeQuery gradeQuery = new TemplateGradeQuery();
			gradeQuery.busdId().eq(district.getId());
			gradeQuery.templateSetId().eq(templateGrade.getTemplateSetId());
			gradeQuery.setSerialNumber(templateGrade.getSerialNumber()-1);
			List<TemplateGradeEntity> templateGrades = this.list(gradeQuery.toQueryWrapper());

			//不降级的等级 直接跳过
			//没有上一级 跳出
			if (templateGrade.getIsDowngrade()==null || !templateGrade.getIsDowngrade()
					|| null == templateGrade.getProtectionDays() || templateGrade.getProtectionDays() <=0
				|| CollectionUtils.isEmpty(templateGrades)){
				continue;
			}

			TemplateGradeEntity beforeGrade = templateGrades.get(0);


			this.whileMemberCardLevel(district.getId(),templateGrade,beforeGrade);
		}
	}

	private void whileMemberCardLevel(String busdId,TemplateGrade templateGrade,TemplateGradeEntity beforeGrade){

		List<MemberCardLevel> memberCardLevels = new ArrayList<>();
		int page = 1;
		while (true){
			PageRequest pageInfo = new PageRequest();
			pageInfo.setSize(2000);
			pageInfo.setPage(page);
			List<MemberCardLevel> levelList = memberCardLevelService.memberCardLevelList(pageInfo,busdId,templateGrade.getId());
			if (CollectionUtils.isEmpty(levelList)){
				break;
			}
			memberCardLevels.addAll(levelList);
			page++;
		}
		LocalDateTime dateTime = LocalDate.now().minusDays(Long.parseLong(templateGrade.getProtectionDays().toString())).atStartOfDay();
		for (MemberCardLevel cardLevel:memberCardLevels){
			this.forMemberCardLevel(busdId,templateGrade,beforeGrade,cardLevel,dateTime);
		}
	}

	private void forMemberCardLevel(String busdId,TemplateGrade templateGrade,TemplateGradeEntity beforeGrade,MemberCardLevel cardLevel,LocalDateTime dateTime){
		if (cardLevel.getEndTime()!=null
				&& cardLevel.getEndTime().compareTo(dateTime) <0){
			StringBuilder reason = new StringBuilder();
			TemplateGradeSetQuery gradeSetQuery = new TemplateGradeSetQuery();
			gradeSetQuery.setTemplateSetId(templateGrade.getTemplateSetId());
			gradeSetQuery.setTemplateGradeId(templateGrade.getId());
			gradeSetQuery.memGradeParamId().isNotNull();
			List<TemplateGradeSetEntity> gradeSets = templateGradeSetService.list(gradeSetQuery.toQueryWrapper());
			if(CollectionUtils.isEmpty(gradeSets)) {
				log.error("当前会员等级未设置会员卡等级条件：会员卡模板设置id={}，会员卡等级ID={}", templateGrade.getTemplateSetId(), templateGrade.getId());
			}
			boolean reachGradeLevel = false;
			if(CollectionUtils.isNotEmpty(gradeSets)) {
				reachGradeLevel = gradeLevelDowngrade(gradeSets,busdId,cardLevel.getMemberId(),reason);
			}
			//没满足条件 降级
			if (Boolean.FALSE.equals(reachGradeLevel)){
				saveMemberDowngrade(beforeGrade,cardLevel,"统一降级");
			}
		}
	}


	private Boolean gradeLevelDowngrade(List<TemplateGradeSetEntity> gradeSets,String busdId,String memberId,StringBuilder reason){
		boolean anyCondition = false;
		boolean allCondition = true;
		for(TemplateGradeSetEntity gradeSet : gradeSets) {
			boolean reachGradeSet = this.reachGradeSet(busdId,memberId,gradeSet,reason);
			// 判断等级条件：0-满足任一条件-ANY、1-满足所有条件-ALL
			if(TemplateGradeSetGradeCondition.ANY.equals(gradeSet.getGradeCondition())) {
				if(reachGradeSet) {
					anyCondition = true;
				}
			} else {
				if(!reachGradeSet) {
					allCondition = false;
				}
			}
		}

		if(TemplateGradeSetGradeCondition.ANY.equals(gradeSets.get(0).getGradeCondition())) {
			return anyCondition;
		} else {
			return allCondition;
		}
	}


	/**
	 * 保存降级
	 * @param beforeGrade
	 * @param memberCardLevel
	 * @param reason
	 */
	private void  saveMemberDowngrade(TemplateGradeEntity beforeGrade,MemberCardLevel memberCardLevel,String reason){
		MemberCardLevel newCardLevel = new MemberCardLevel();
		newCardLevel.setGradeId(beforeGrade.getId());
		newCardLevel.setGradeName(beforeGrade.getName());
		newCardLevel.setModifiedTime(LocalDateTime.now());
		newCardLevel.setBeginTime(LocalDateTime.now());
		if (null != beforeGrade.getIsDowngrade() && beforeGrade.getIsDowngrade()
				&& beforeGrade.getProtectionDays()!=null
				&& beforeGrade.getProtectionDays()>0){
			newCardLevel.setEndTime(newCardLevel.getBeginTime().plusDays(Long.parseLong(beforeGrade.getProtectionDays().toString())));
		}
		MemberCardLevelQuery cardLevelQuery = new MemberCardLevelQuery();
		cardLevelQuery.setId(memberCardLevel.getId());
		memberCardLevelService.update(newCardLevel, cardLevelQuery.toQueryWrapper());

		// 清除缓存
		memberCardLevelService.evict(memberCardLevel.getBusdId(), memberCardLevel.getMemberId());

		// 创建会员等级更新日志
		MemberGradeLogEntity gradeLog = new MemberGradeLogEntity();
		gradeLog.setId(IdWorker.getIdStr());
		gradeLog.setBusdId(memberCardLevel.getBusdId());
		gradeLog.setMemberId(memberCardLevel.getMemberId());
		gradeLog.setType(MemberGradeLogType.VIP_DEMOTION);
		gradeLog.setGradeRule(MemberGradeLogGradeRule.from(beforeGrade.getGradeRule().getCode()));
		gradeLog.setBeforeGradeId(memberCardLevel.getGradeId());
		gradeLog.setBeforeGrade(memberCardLevel.getGradeName());
		gradeLog.setAlferGradeId(beforeGrade.getId());
		gradeLog.setAfterGrade(beforeGrade.getName());
		gradeLog.setReason(reason);
		gradeLog.setCreatedTime(LocalDateTime.now());
		memberGradeLogService.save(gradeLog);

	}

	/**
	 * 判断是否达到会员等级条件
	 * @param busdId
	 * @param memberId
	 * @param gradeSet
	 * @param reason
	 * @return
	 */
	private boolean reachGradeSet(String busdId, String memberId, TemplateGradeSetEntity gradeSet, StringBuilder reason) {
		boolean reachGradeSet = false;
		// 获取会员卡等级条件参数
		TemplateGradeParam gradeParam = templateGradeParamService.getTemplateGradeParam(gradeSet.getTemplateSetId(),gradeSet.getTemplateGradeId(),gradeSet.getMemGradeParamId());
		if(null == gradeParam) {
			log.error("根据会员卡等级条件参数id未获取到参数信息：会员卡等级条件参数ID={}");
			return reachGradeSet;
		}

		if(TemplateGradeParamParamType.ONLINE_MONEY.getCode().equals(gradeParam.getParamType().getCode()) || TemplateGradeParamParamType.OFFLINE_MONEY.getCode().equals(gradeParam.getParamType().getCode())) {
			// 判断是否达到线上消费金额条件
			reachGradeSet = reachOnlineMoneyAmount(busdId, memberId, gradeParam,gradeParam.getParamType());
		} else if(TemplateGradeParamParamType.CONSUME_TIMES.getCode().equals(gradeParam.getParamType().getCode()) || TemplateGradeParamParamType.OFFLINE_TIMES.getCode().equals(gradeParam.getParamType().getCode())) {
			// 判断是否达到最近消费次数条件
			reachGradeSet = reachConsumeTimes(busdId, memberId, gradeParam,gradeParam.getParamType());
		} else if(TemplateGradeParamParamType.OFFLINE_SCORE.getCode().equals(gradeParam.getParamType().getCode()) || TemplateGradeParamParamType.ONLINE_SCORE.getCode().equals(gradeParam.getParamType().getCode())) {
			// 判断是否达到线下积分条件
			reachGradeSet = reachOfflineScore(busdId, memberId, gradeParam,gradeParam.getParamType());
		}

		reason.append("[" + gradeParam.getParamType().getAlias() + "|" + gradeParam.getName() + "|" + reachGradeSet + "]");
		return reachGradeSet;
	}

	/**
	 * 判断是否达到线上消费金额条件
	 * @return
	 */
	private boolean reachOnlineMoneyAmount(String busdId, String memberId, TemplateGradeParam gradeParam,TemplateGradeParamParamType type) {
		boolean onlineMoney = false;

		OrderMemberGradeQuery query = new OrderMemberGradeQuery();
		query.setBusdId(busdId);
		query.setMemberId(memberId);
		if (type == TemplateGradeParamParamType.ONLINE_MONEY){
			query.setType(1);
		}else if (type == TemplateGradeParamParamType.OFFLINE_MONEY){
			query.setType(2);
		}
		// 累计积分
		if(!TemplateGradeParamTimeAccuracy.ALL.equals(gradeParam.getTimeAccuracy())) {
			query.setCreateTimeBetweenS(getTimeByParam(gradeParam.getTimeAccuracy(), gradeParam.getTimeSize()));
			query.setCreateTimeBetweenE(LocalDateTime.now());
		}
		BigDecimal amount = orderService.getOrderOnlineMoneyByMemberId(query);
		// 会员指定条件累计金额满足参数条件
		if(amount.compareTo(gradeParam.getAmount()) >= 0) {
			onlineMoney = true;
		}

		return onlineMoney;
	}

	/**
	 * 判断是否达到最近消费次数条件
	 * @return
	 */
	private boolean reachConsumeTimes(String busdId, String memberId, TemplateGradeParam gradeParam,TemplateGradeParamParamType type) {
		boolean consumeTimes = false;

		OrderMemberGradeQuery query = new OrderMemberGradeQuery();
		query.setBusdId(busdId);
		query.setMemberId(memberId);
		if (type == TemplateGradeParamParamType.CONSUME_TIMES){
			query.setType(1);
		}else if (type == TemplateGradeParamParamType.OFFLINE_TIMES){
			query.setType(2);
		}
		// 累计积分
		if(TemplateGradeParamTimeAccuracy.ALL.equals(gradeParam.getTimeAccuracy())) {
			query.setCreateTimeBetweenS(getTimeByParam(gradeParam.getTimeAccuracy(), gradeParam.getTimeSize()));
			query.setCreateTimeBetweenE(LocalDateTime.now());
		}
		BigDecimal times = orderService.getOrderConsumeTimesByMemberId(query);
		// 会员指定条件累计金额满足参数条件
		if(times.compareTo(gradeParam.getAmount()) >= 0) {
			consumeTimes = true;
		}

		return consumeTimes;
	}

	/**
	 * 判断是否达到线下积分条件
	 * @return
	 */
	private boolean reachOfflineScore(String busdId, String memberId, TemplateGradeParam gradeParam,TemplateGradeParamParamType type) {
		boolean offlineScore = false;

		PointSumQuery sumQuery = new PointSumQuery();
		sumQuery.setBusdId(busdId);
		sumQuery.setMemberId(memberId);
		if (type == TemplateGradeParamParamType.OFFLINE_SCORE){
			sumQuery.setType(1);
		}else if (type == TemplateGradeParamParamType.ONLINE_SCORE){
			sumQuery.setType(2);
		}
		// 累计积分
		if(!TemplateGradeParamTimeAccuracy.ALL.equals(gradeParam.getTimeAccuracy())) {
			sumQuery.setCreateTimeBetweenS(getTimeByParam(gradeParam.getTimeAccuracy(), gradeParam.getTimeSize()));
			sumQuery.setCreateTimeBetweenE(LocalDateTime.now());
		}
		BigDecimal sumPoints = detailService.getSumPointsByMemberId(sumQuery);
		// 会员指定条件累计积分满足参数条件
		if(sumPoints.compareTo(gradeParam.getAmount()) >= 0) {
			offlineScore = true;
		}

		return offlineScore;
	}

	/**
	 * 获取指定范围的时间点
	 * @param timeAccuracy
	 * @param timeSize
	 * @return
	 */
	private LocalDateTime getTimeByParam(TemplateGradeParamTimeAccuracy timeAccuracy, Integer timeSize) {
		LocalDateTime now = LocalDateTime.now();
		LocalDateTime time = null;
		if(TemplateGradeParamTimeAccuracy.YEAR.getCode().equals(timeAccuracy.getCode())) {
			time = now.minusYears(timeSize);
		} else if(TemplateGradeParamTimeAccuracy.MONTH.getCode().equals(timeAccuracy.getCode())) {
			time = now.minusMonths(timeSize);
		} else if(TemplateGradeParamTimeAccuracy.DAY.getCode().equals(timeAccuracy.getCode())) {
			time = now.minusDays(timeSize);
		}
		return time;
	}

	@Override
	public TemplateGrade getFirst(TemplateGradeQuery gradeQuery){
		List<TemplateGradeEntity> list = this.list(gradeQuery.toQueryWrapper());
		if (CollectionUtils.isNotEmpty(list)){
			return new TemplateGrade(list.get(0));
		}
		return new TemplateGrade();
	}


}